//
//  QsbkOnlyContextViewController.m
//  NewProject
//
//  Created by Livespro on 2017/4/27.
//  Copyright © 2017年 FZ. All rights reserved.
//

#import "QsbkOnlyContextViewController.h"
#import "QsbkOnlyContextViewModel.h"

#import "QsbkOnlyContextTableViewCell.h"

#import "ZFPlayer.h"

@interface QsbkOnlyContextViewController ()<UITableViewDelegate,UITableViewDataSource,DZNEmptyDataSetSource,ZFPlayerDelegate>

@property (nonatomic, strong)  UITableView *contentTableView;

@property (nonatomic, strong)  QsbkOnlyContextViewModel *viewModel;


@property (nonatomic, strong) ZFPlayerView        *playerView;
@property (nonatomic, strong) ZFPlayerControlView *controlView;

@end

@implementation QsbkOnlyContextViewController

- (QsbkOnlyContextViewModel *)viewModel{
    
    if (!_viewModel) {
        
        _viewModel = [[QsbkOnlyContextViewModel alloc]init];
    }
    
    return _viewModel;
}

- (UITableView *)contentTableView{
    
    if (!_contentTableView) {
        _contentTableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 64, kScreenWidth, kScreenHeight - 64) style:UITableViewStyleGrouped];
        
        _contentTableView.delegate = self;
        _contentTableView.dataSource = self;
        _contentTableView.emptyDataSetSource = self;
        _contentTableView.showsHorizontalScrollIndicator = NO;
        _contentTableView.showsVerticalScrollIndicator  = NO;
        _contentTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _contentTableView.backgroundColor=pageColor;
        
        [self setUpRefreshWithScrollView:_contentTableView];
        
        [_contentTableView registerClass:[QsbkOnlyContextTableViewCell class] forCellReuseIdentifier:NSStringFromClass([QsbkOnlyContextTableViewCell class])];
        
    }
    return _contentTableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)staticViewsWithoutNib;{
    
    self.naviStand.title = Qsbk_NamesArray[_currentType];
    
    [self addBack];
    
    [self.view addSubview:self.contentTableView];
    
}

- (void)back{
    
    if (self.backPass) {
        self.backPass();
    }
}

- (void)loadData;{
    
    __weak typeof(self) weakSelf = self;
    self.status = BaseShowStatusLoading;
    [self.viewModel qsbkOnlyContextType:RefreshTypeRenew  Module:Qsbk_ModuleArray[_currentType] Result:^(BOOL isSuccess, NSString *desc) {
        weakSelf.status = BaseShowStatusDefault;
        [weakSelf showHint:@"获取30条数据"];
        [weakSelf.contentTableView reloadData];
    }];
    
}


#pragma mark - tableViewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return self.viewModel.contextDataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;{
    
    return 1;
}

#pragma mark - cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;{
    
    QsbkOnlyContextTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([QsbkOnlyContextTableViewCell class]) forIndexPath:indexPath];
    
    __block QsbkOnlyContextModel *model = self.viewModel.contextDataArray[indexPath.section];
    
    cell.model = model;
    
    //播放...
    
    __block NSIndexPath *weakIndexPath = indexPath;
    __block QsbkOnlyContextTableViewCell *weakCell     = cell;
    __weak typeof(self)  weakSelf      = self;
    // 点击播放的回调
    cell.videoCallBack = ^(){
        
        // 分辨率字典（key:分辨率名称，value：分辨率url)
        NSMutableDictionary *dic = @{}.mutableCopy;
        if (model.low_url) {
          
            [dic setValue:model.low_url forKey:@"流畅"];
        }
        if (model.high_url) {
            
            [dic setValue:model.high_url forKey:@"高清"];
        }
        // 取出字典中的第一视频URL
        NSURL *videoURL = [NSURL URLWithString:dic.allValues.firstObject];

        ZFPlayerModel *playerModel  = [[ZFPlayerModel alloc] init];
        playerModel.title           = model.content;
        playerModel.videoURL        = videoURL;
//        playerModel.placeholderImageURLString = model.coverForFeed;
        playerModel.scrollView       = weakSelf.contentTableView;
        playerModel.indexPath       = weakIndexPath;
        // 赋值分辨率字典
        playerModel.resolutionDic    = dic;
        // player的父视图tag
        playerModel.fatherView      = (UIImageView *)[weakCell valueForKey:@"contextImg"];
        
        playerModel.fatherViewTag = 10010;
        
        // 设置播放控制层和model
        [weakSelf.playerView playerControlView:nil playerModel:playerModel];
        // 下载功能
//        weakSelf.playerView.hasDownload = YES;
        // 自动播放
        [weakSelf.playerView autoPlayTheVideo];
    };
    
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    QsbkOnlyContextModel *model = self.viewModel.contextDataArray[indexPath.section];
    
    return model.cellHeight;
}

#pragma mark - header,footer
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return .01f;
}

#pragma mark - empty
- (nullable UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView;{
    
    return [UILabel labelWithText:@"没找到笑话吖~" TextFont:15 TextColor:Color333 Frame:CGRectMake(0, 0, kScreenWidth, 20) NumberOfLines:1 TextAlignment:NSTextAlignmentCenter BackgroundColor:[UIColor clearColor]];
}

#pragma mark - 刷新
- (void)headerRefresh:(MJRefreshNormalHeader *)header;{

    __weak typeof(self) weakSelf = self;
    [self.viewModel qsbkOnlyContextType:RefreshTypeRenew  Module:Qsbk_ModuleArray[_currentType] Result:^(BOOL isSuccess, NSString *desc) {
        
        [weakSelf.contentTableView.mj_header endRefreshing];
        
        [weakSelf.contentTableView reloadData];
    }];
}

- (void)footerRefresh:(MJRefreshAutoNormalFooter *)footer;{

    __weak typeof(self) weakSelf = self;
    [self.viewModel qsbkOnlyContextType:RefreshTypeAdd  Module:Qsbk_ModuleArray[_currentType] Result:^(BOOL isSuccess, NSString *desc) {
        
        [weakSelf.contentTableView.mj_footer endRefreshing];
        
        [weakSelf.contentTableView reloadData];
    }];
}



- (ZFPlayerView *)playerView {
    if (!_playerView) {
        _playerView = [ZFPlayerView sharedPlayerView];
//        _playerView.delegate = self;
        // 当cell播放视频由全屏变为小屏时候，不回到中间位置
        _playerView.cellPlayerOnCenter = NO;
        
//         当cell划出屏幕的时候停止播放
         _playerView.stopPlayWhileCellNotVisable = YES;
//        （可选设置）可以设置视频的填充模式，默认为（等比例填充，直到一个维度到达区域边界）
         _playerView.playerLayerGravity = ZFPlayerLayerGravityResizeAspect;
//         静音
//         _playerView.mute = YES;
    }
    return _playerView;
}

- (ZFPlayerControlView *)controlView {
    if (!_controlView) {
        _controlView = [[ZFPlayerControlView alloc] init];
    }
    return _controlView;
}

#pragma mark - ZFPlayerDelegate

- (void)zf_playerDownload:(NSString *)url {
    // 此处是截取的下载地址，可以自己根据服务器的视频名称来赋值
    NSString *name = [url lastPathComponent];
//    [[ZFDownloadManager sharedDownloadManager] downFileUrl:url filename:name fileimage:nil];
//    // 设置最多同时下载个数（默认是3）
//    [ZFDownloadManager sharedDownloadManager].maxCount = 4;
}

@end
